﻿using System.Linq;
using System.Security.Cryptography;
using System.Text;
using ECatalog.Models;

namespace ECatalog.Controllers
{
    public class AuthorizationService
    {
        public virtual bool ValidateUser(string username, string password)
        {
            using (var db = new DbContainer())
            {
                if (username == "admin")
                {
                    var admin = db.Users.FirstOrDefault(x => x.Login == username && x.Password == password);
                    if (admin == null)
                    {
                        var u = new User
                            {
                                Login = "admin",
                                Password = "admin",
                                IsAdmin = true
                            };
                        db.Users.Add(u);
                        db.SaveChanges();
                    }
                    else
                    {
                        return true;
                    }
                }
                else
                {
                    password = AppHelper.HashAndSolt(password);    
                }
                var user = db.Users.FirstOrDefault(x => x.Login == username && x.Password == password);
                if (user!=null)
                {
                    return true;
                }
            }
            return false;
        }
    }

    public static class AppHelper
    {
        public static string HashAndSolt(string password)
        {
            const string allagreed = "ecatalog";
            password = password + allagreed;
            var hash = MD5.Create().ComputeHash(Encoding.ASCII.GetBytes(password));
            var str = "";
            var numArray = hash;
            var index = 0;
            while (index < numArray.Length)
            {
                var num = numArray[index];
                str = str + num.ToString("x2");
                checked
                {
                    ++index;
                }
            }

            return str;
        }
    }
}